/**
 * 病历相关 API
 */
import request, { ResponseData, PaginatedResponse } from '@/utils/request';

// 病历基本信息
export interface MedicalRecord {
  id: string;
  patient_name: string;
  patient_age?: number;
  patient_gender?: string;
  patient_card_number?: string;
  department?: string;
  visit_date?: string;
  chief_complaint?: string;
  present_illness?: string;
  diagnosis?: string[];
  doctor_name?: string;
  created_at: string;
  updated_at: string;
}

// 病历列表项
export interface RecordListItem {
  id: string;
  patient_name: string;
  patient_gender?: string;
  patient_age?: number;
  department?: string;
  visit_date?: string;
  diagnosis?: string[];
  created_at: string;
  has_assessment: boolean;
}

// 用药信息
export interface Medication {
  id: string;
  medication_name: string;
  specification?: string;
  route?: string;
  frequency?: string;
  dosage_value?: number;
  dosage_unit?: string;
  duration?: number;
  total_quantity?: string;
}

// 医嘱信息
export interface Instruction {
  id: string;
  instruction_text: string;
  instruction_type?: string;
}

// 病历详情
export interface RecordDetail extends MedicalRecord {
  medications: Medication[];
  instructions: Instruction[];
  raw_data: any;
}

// 上传响应
export interface UploadResponse {
  success_count: number;
  failed_count: number;
  records: MedicalRecord[];
  errors: Array<{ filename: string; error: string }>;
}

// 查询参数
export interface RecordQueryParams {
  patient_name?: string;
  department?: string;
  has_assessment?: boolean;
  page?: number;
  page_size?: number;
}

// 统计信息
export interface RecordStatistics {
  total_records: number;
  assessed_records: number;
  pending_records: number;
}

/**
 * 上传病历文件
 */
export const uploadRecords = (files: FileList | File[]) => {
  const formData = new FormData();
  Array.from(files).forEach((file) => {
    formData.append('files', file);
  });
  
  return request.post<ResponseData<UploadResponse>>(
    '/records/upload',
    formData,
    {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    }
  );
};

/**
 * 获取病历列表
 */
export const getRecordsList = (params: RecordQueryParams) => {
  return request.get<ResponseData<PaginatedResponse<RecordListItem>>>(
    '/records/list',
    { params }
  );
};

/**
 * 获取病历详情
 */
export const getRecordDetail = (recordId: string) => {
  return request.get<ResponseData<RecordDetail>>(`/records/${recordId}`);
};

/**
 * 删除病历
 */
export const deleteRecord = (recordId: string) => {
  return request.delete<ResponseData<{ record_id: string }>>(
    `/records/${recordId}`
  );
};

/**
 * 获取统计信息
 */
export const getRecordStatistics = () => {
  return request.get<ResponseData<RecordStatistics>>(
    '/records/statistics/summary'
  );
};
